<script setup lang="ts">
import { useUserInfoStore } from '@/store/userInfo'

import modalSuccessIcon from '@/static/images/modal/success.png'
import { fetchStaffGroupAPI } from '@/apis/fetchStaffGroup'
import { fetchStaffListAPI } from '@/apis/fetchStaffList'
import { updateForemanAPI } from '@/apis/updateForeman'
import { verifyProjectAPI } from '@/apis/verifyProject'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const isInitial = ref(false)

const projectId = ref('')

const staffGroupList = ref<StaffGroup[]>([])
const foremanGroup = ref<StaffGroup | null>(null)

const foremans = ref<Staff[] | null>(null)
const selectedForeman = ref<Staff | null>(null)

const loading = ref(true)
const isShowSuccessModal = ref(false)

onLoad(async (options) => {
  if (options && options.project_id) {
    projectId.value = options.project_id
    const res = await fetchStaffGroupAPI()
    staffGroupList.value = res.data?.data || []
    foremanGroup.value = staffGroupList.value.find(el => el.name === '工长')!
    foremans.value = await loadForemans(foremanGroup.value) || []
    loading.value = false

    // 如果是审批项目时第一次分配工长，标记一下
    isInitial.value = options.is_initial === 'true'
  }
  else {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
    loading.value = false
  }
})

async function loadForemans(group: StaffGroup) {
  const group_id = group.id
  if (group_id) {
    try {
      const res = await fetchStaffListAPI({ group_id: `${group_id}` }, userInfoStore.userInfo!.token!)
      return res.data?.data
    }
    catch (err) {
      uni.showToast({ title: '获取数据失败', icon: 'none' })
    }
  }
}

/* ------------------------------- 事件处理 START ------------------------------- */
const handleSearch = useDebounceFn(async (keyword: string) => {
  const group_id = foremanGroup.value?.id
  if (group_id) {
    uni.showLoading({ title: '搜索中...' })
    try {
      const res = await fetchStaffListAPI({
        group_id: `${group_id}`,
        keyword,
      }, userInfoStore.userInfo!.token!)
      uni.hideLoading()
      foremans.value = res.data?.data || []
    }
    catch (err) {
      uni.showToast({ title: '获取数据失败', icon: 'none' })
    }
  }
}, 500)

function handleSelect(foreman: Staff) {
  selectedForeman.value = foreman
}

const handleSubmit = useThrottleFn(async () => {
  if (selectedForeman.value && selectedForeman.value.id) {
    try {
      if (isInitial.value) {
        const res = await verifyProjectAPI({
          project_id: projectId.value,
          verify: '2',
          foreman_id: selectedForeman.value!.id!.toString()!,
        }, userInfoStore.userInfo!.token!)
        if (res.data?.code === 1)
          isShowSuccessModal.value = true
        else uni.showToast({ title: res.data?.msg, icon: 'none' })
      }
      else {
        const res = await updateForemanAPI({
          project_id: projectId.value,
          foreman_id: selectedForeman.value!.id!.toString()!,
        }, userInfoStore.userInfo!.token!)
        if (res.data?.code === 1)
          isShowSuccessModal.value = true
        else
          uni.showToast({ title: res.data?.msg, icon: 'none' })
      }
    }
    catch {
      uni.showToast({ title: '出现异常，请重试', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '出现异常，请重试', icon: 'none' })
  }
}, 500)

function handleExit() {
  router.back()
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <view class="relative min-h-screen bg-#F8F8F8">
    <view class="z-100 sticky top-0 left-0 w-750rpx bg-white">
      <Spacer height="30" />
      <view class="mx-30rpx border-1px border-solid border-#E3E3E3 rounded-6rpx">
        <uv-search
          shape="square" bg-color="#F8F9FD" color="#000000" search-icon-size="36rpx"
          search-icon-color="#FF6D0A" placeholder-color="#999999" :show-action="false"
          height="74rpx" placeholder="请输入员工姓名/手机号"
          @change="handleSearch"
        />
      </view>
      <Spacer height="10" />
      <uv-tabs
        :list="[{ name: '工长' }]" line-color="#FF6D0A" line-width="48rpx"
        :active-style="{ color: '#000000', fontSize: '32rpx', lineHeight: '32rpx' }"
        :inactive-style="{ color: '#999999', fontSize: '28rpx', lineHeight: '28rpx' }"
        :custom-style="{ margin: '0 10rpx' }"
      />
    </view>
    <uv-list v-if="foremans && foremans.length > 0" :custom-style="{ padding: '30rpx 0', backgroundColor: '#F8F8F8' }">
      <uv-list-item v-for="foreman, index in foremans" :key="index" :custom-style="{ borderRadius: '20rpx' }">
        <PersonItem
          :is-show-checkbox="true"
          :is-selected="selectedForeman === foreman"
          :avatar="foreman.avatar || 'http://jzt.tykhrs.cn/uploads/20240204/87b5977293b9856b96b77b21dcfc3e2a.png'"
          :name="foreman.nickname || '未知'"
          identity="工长"
          :phone-number="foreman.mobile || '未知'"
          @tap="handleSelect(foreman)"
        />
        <Divider />
      </uv-list-item>
    </uv-list>
    <PageDefault v-else />
    <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
    <RGButton class="fixed bottom-80rpx x-center" @tap="handleSubmit">
      确定选择
    </RGButton>
    <uv-overlay :show="isShowSuccessModal" @tap="handleExit">
      <uv-transition mode="zoom-in" :show="isShowSuccessModal">
        <view class="relative w-screen h-screen">
          <JZTModal :icon="modalSuccessIcon" title="分配成功" content="工长分配成功" @confirm="handleExit" />
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
</template>

<route lang="yaml">
name: 'assignForeman'
style:
  navigationBarTitleText: '分配工长'
layout: 'custom'
</route>
